package com.ch.sys.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ch.sys.common.Constants;
import com.ch.sys.model.Employee;


public class LoginInterceptor extends HandlerInterceptorAdapter  {
	
	//登录页面 请求路径
	private static final String loginApi = "/employee/login";
	private static final String loginPage = "/admin/login";
	private static final String indexPage = "/admin/index";
	private static final String restApi = "/api/";

	/**
	 * controller 之前  执行
	 * return false  postHandle  afterCompletion 都不会执行
	 * return true 放行
	 */
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
//		request.setCharacterEncoding("utf8");
		
		//过滤特殊请求
		String requestURI = request.getRequestURI();
		String contentPath = request.getContextPath();
		Employee employee = SessionUtils.get(request);
		
		//API接口 一律放行
		//已经登陆且调用app，pass
		if(isPage(Constants.REST_APP_URL, requestURI) ) {
			return true;
		}
		
		//登陆接口，pass
		if( requestURI.indexOf(loginApi) != -1 || requestURI.indexOf(restApi) != -1) {
			return true;
		}
		//已经登陆且调用webapi，pass
		if( employee != null && isPage(Constants.REST_WEB_URL, requestURI) ) {
			return true;
		}
		
		//如果未登陆，且在登陆页面, pass
		else if( employee == null && isPage(loginPage, requestURI) ) {
			return true;
		}
		
		//已经登陆，且在登陆页面，进入首页
		else if( employee != null && isPage(loginPage, requestURI) ) {
			response.sendRedirect(contentPath + indexPage);
			return false;
		}
		//未登录且访问非登陆页面，跳转到登陆页面
		/*else if( employee == null && !isPage(loginPage, requestURI) ) {
			response.sendRedirect(contentPath + loginPage);
			return false;
		}*/
		
		return true;
	}
	
	public Boolean isPage(String page, String requestURI) {
		return requestURI.indexOf(page) != -1;
	}

	/**
	 * 生成视图之前 执行
	 */
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	/**
	 * 生成视图之后，紧接步骤是返回给客户端
	 */
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
}
